package com.example.order.converter;

import com.example.order.dataObject.OrderDetail;
import com.example.order.dto.OrderDTO;
import com.example.order.enums.ResultEnum;
import com.example.order.exeception.OrderExeception;
import com.example.order.from.OrderFrom;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class OrderFrom2OrderDTO {
    public static OrderDTO convert(OrderFrom orderFrom) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderFrom.getName());
        orderDTO.setBuyerPhone(orderFrom.getPhone());
        orderDTO.setBuyerAddress(orderFrom.getAddress());
        orderDTO.setBuyerOpenid(orderFrom.getOpenid());

        List<OrderDetail> list = new ArrayList<>();
        try {
            Gson gson = new Gson();
            list =   gson.fromJson(orderFrom.getItems(), new TypeToken<List<OrderDetail>>() {
            }.getType());
        } catch (Exception e) {
            //json转换错误
            throw  new OrderExeception(ResultEnum.PARAM_ERROR);
        }

        orderDTO.setOderDetaillist(list);

        return orderDTO;
    }
}
